package com.news.news.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by 罗铠威 on 2023/9/2 17:54
 * type:
 */
@Component
@Aspect
public class LogAspect{
    private Logger logger = LoggerFactory.getLogger(getClass());
    //通配符，定义规则，哪些方法可以被我的切面切到，这里的意思是不限返回值和方法和参数
    @Pointcut("execution(public * com.ffyc.news.controller..*.*(..))")
    public void webLog() {
    }
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
        logger.info("HTTP_METHOD :{} ", request.getMethod());
        logger.info("IP : {}", request.getRemoteAddr());
//获取所有请求参数
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            logger.info("name:{},value:{}", name, request.getParameter(name));
        }
    }
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfter(Object ret) throws Throwable {
// 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
    }
}
